﻿using RobotPerCeption.Entity;

namespace Nex_CSharp_Demo.utils
{
    public class ThreadUtils
    {
        public static Dictionary<int, PositionThreadInfo> positonThread = new Dictionary<int, PositionThreadInfo>();



        public static int addThread(int position, Thread thread, CancellationToken cts, CancellationTokenSource source)
        {

            int manageId = thread.ManagedThreadId;
            lock (positonThread)
            {
                if (!positonThread.ContainsKey(position))
                {
                    PositionThreadInfo info = new PositionThreadInfo(position, thread, manageId, cts, source);
                    positonThread.Add(position, info);
                    return manageId;
                }

            }
            return manageId;
        }



        public static PositionThreadInfo? FindThreadSource(int positionId)
        {




            if (positonThread.ContainsKey(positionId))
            {
                return positonThread.TryGetValue(positionId, out PositionThreadInfo result) ? result : null;
            }

            return null;




        }


        public static bool removeThread(PositionThreadInfo position)
        {

            if (position != null)
            {


                if (ThreadUtils.positonThread.Count > 0)
                {

                    if (positonThread.ContainsKey(position.cur_robote_position))
                    {
                        CancellationToken cur = position.cts;
                        CancellationTokenSource source = position.source;
                        ThreadUtils.positonThread.Remove(position.cur_robote_position);
                        stopThread(position.thread, cur, source);

                        return true;
                    }

                }


            }
            return false;

        }


        public static bool stopThread(Thread cur_thread, CancellationToken cur_cts, CancellationTokenSource source)
        {



            if (!cur_cts.IsCancellationRequested)
            {
                source.Cancel();
            }
            /* cur_thread.Join();
             Thread.Sleep(1000);*/
            return true;



        }


        public static int keyItratorRemove()
        {
            int removeCount = 0;
            Dictionary<int, PositionThreadInfo>.KeyCollection c = positonThread.Keys;
            foreach (int s in c)
            {

                removeCount++;
                PositionThreadInfo p = FindThreadSource(s);
                if (p != null)
                {
                    stopThread(p.thread, p.cts, p.source);
                }
                positonThread.Remove(s);


            }
            return removeCount;

        }
    }
}
